package proxyMethod.Demo;

import proxyMethod.BookStore;
import proxyMethod.Impl.BookStoreHandler;
import proxyMethod.Impl.BookStoreProxy;
import proxyMethod.Impl.RealBookStore;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Proxy;
import java.util.HashMap;
import java.util.Hashtable;

public class ProxyDemo {
    public static void main(String[] args) {
        System.out.println("-------静态代理---------");
        BookStore adminBookStore = new BookStoreProxy(true);
        BookStore userBookStore = new BookStoreProxy(false);

        System.out.println("管理员:");
        adminBookStore.displayBookDetails("12345");

        System.out.println("\n普通用户:");
        userBookStore.displayBookDetails("12345");
        System.out.println("-------动态代理--------");
        RealBookStore realBookStore = new RealBookStore();
        InvocationHandler handler = new BookStoreHandler(realBookStore);

        // 使用Java的Proxy类创建动态代理对象
        BookStore proxyBookStore = (BookStore) Proxy.newProxyInstance(
                realBookStore.getClass().getClassLoader(),
                realBookStore.getClass().getInterfaces(),
                handler
        );

        // 通过代理对象调用方法
        proxyBookStore.displayBookDetails("12345");
    }
}

class MapComparisonDemo {
    public static void main(String[] args) {
        Hashtable<String, String> hashtable = new Hashtable<>();
        HashMap<String, String> hashMap = new HashMap<>();

        Thread hashtableThread1 = new Thread(() -> {
            for (int i = 0; i < 50; i++) {
                hashtable.put("thread1Key" + i, "thread1Value" + i);
            }
        });

        Thread hashtableThread2 = new Thread(() -> {
            for (int i = 0; i < 50; i++) {
                hashtable.put("thread2Key" + i, "thread2Value" + i);
            }
        });

        Thread hashMapThread1 = new Thread(() -> {
            for (int i = 0; i < 50; i++) {
                hashMap.put("thread1Key" + i, "thread1Value" + i);
            }
        });

        Thread hashMapThread2 = new Thread(() -> {
            for (int i = 0; i < 50; i++) {
                hashMap.put("thread2Key" + i, "thread2Value" + i);
            }
        });

        // 启动线程
        hashtableThread1.start();
        hashtableThread2.start();
        hashMapThread1.start();
        hashMapThread2.start();

        // 等待线程完成
        try {
            hashtableThread1.join();
            hashtableThread2.join();
            hashMapThread1.join();
            hashMapThread2.join();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        // 打印Hashtable和HashMap的大小
        System.out.println("Hashtable size: " + hashtable.size()); // 输出应为100
        System.out.println("HashMap size: " + hashMap.size()); // 输出可能小于100
    }
}